/*
 * MegaMek - Copyright (C) 2000,2001,2002,2003,2004 Ben Mazur (bmazur@sev.org)
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the Free
 *  Software Foundation; either version 2 of the License, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *  for more details.
 */

/*
 * DfaAttackAction.java
 *
 * Created on March 16, 2002, 11:43 AM
 */

package megamek.common.actions;

import java.util.Enumeration;

import megamek.common.BattleArmor;
import megamek.common.BipedMech;
import megamek.common.Compute;
import megamek.common.Coords;
import megamek.common.CriticalSlot;
import megamek.common.Entity;
import megamek.common.EntityWeightClass;
import megamek.common.GunEmplacement;
import megamek.common.IEntityMovementType;
import megamek.common.IGame;
import megamek.common.Infantry;
import megamek.common.Mech;
import megamek.common.MiscType;
import megamek.common.MovePath;
import megamek.common.MoveStep;
import megamek.common.Player;
import megamek.common.Tank;
import megamek.common.TargetRoll;
import megamek.common.Targetable;
import megamek.common.ToHitData;
import megamek.common.VTOL;
import megamek.common.IBoard;
import megamek.common.IHex;
import megamek.common.Pilot;
import megamek.common.options.GameOptions;

// TODO: Auto-generated Javadoc
/**
 * The Class DfaAttackAction.
 *
 * @author Ben
 * @version 
 */
public class DfaAttackAction extends DisplacementAttackAction {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 3953889779582616903L;
  
  	
    
    /**
     *  Creates new DfaAttackAction.
     *
     * @param entityId the entity id
     * @param targetId the target id
     * @param targetPos the target pos
     */
    public DfaAttackAction(final int entityId, final int targetId, final Coords targetPos) {
        super(entityId, targetId, targetPos);
    }

    /**
     * Instantiates a new dfa attack action.
     *
     * @param entityId the entity id
     * @param targetType the target type
     * @param targetId the target id
     * @param targetPos the target pos
     */
    public DfaAttackAction(final int entityId, final int targetType, final int targetId,
           final Coords targetPos) {
        super(entityId, targetType, targetId, targetPos);
    }

    /**
     * Damage done to a mech after a successful DFA.
     *
     * @param entity the entity
     * @return the damage taken by
     */
    public static int getDamageTakenBy(final Entity entity) {
        return (int) Math.ceil(entity.getWeight() / 5.0);
    }

    /**
     * Damage that a mech does with a successful DFA.
     *
     * @param entity the entity
     * @param targetInfantry the target infantry
     * @return the damage for
     */
    public static int getDamageFor(final Entity entity, final boolean targetInfantry) {
        int toReturn = (int) Math.ceil((entity.getWeight() / 10.0) * 3.0);

        if ( hasTalons(entity) ) {
            toReturn *= 1.5;
        }

        if (targetInfantry) {
            toReturn = Math.max(1, toReturn / 10);
        }
        return toReturn;

    }

    /**
     * Checks if a death from above attack can hit the target, including
     * movement.
     *
     * @param game the game
     * @param attackerId the attacker id
     * @param target the target
     * @param md the md
     * @return the to hit data
     */
    public static ToHitData toHit(final IGame game, final int attackerId,
            final Targetable target, final MovePath md) {
    	ToHitData hitData = null; 
    	 	Boolean premReturn = false; 
        

        // Do to pretreatment of physical attacks, the target may be null.
        if (target == null) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE, "Target is null");
        	premReturn = true;
        	
        }

        Entity targetEntity = null;
        if (target.getTargetType() == Targetable.TYPE_ENTITY) {
            targetEntity = (Entity) target;
        }
        final Entity attackEntity = game.getEntity(attackerId);
        Coords chargeSrc = attackEntity.getPosition();
        MoveStep chargeStep = null;

        // Infantry CAN'T dfa!!!
        if (attackEntity instanceof Infantry) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE, "Infantry can't D.F.A.");
        	premReturn = true;
        }

        if (attackEntity.getJumpType() == Mech.JUMP_BOOSTER) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"Can't D.F.A. using mechanical jump boosters.");
    		premReturn = true;
        }

        // let's just check this
        if (!md.contains(MovePath.STEP_DFA)) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"D.F.A. action not found in movment path");
    		premReturn = true;
        }

        // have to jump
        if (!md.contains(MovePath.STEP_START_JUMP)) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"D.F.A. must involve jumping");
    		premReturn = true;
        }

        // Can't target a transported entity.
        if ((targetEntity != null) && (Entity.NONE != targetEntity.getTransportId())) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is a passenger.");
    		premReturn = true;
        }

        //no evading
        if(md.contains(MovePath.STEP_EVADE)) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE, "No evading while charging");
    		premReturn = true;
        }

        // Can't target a entity conducting a swarm attack.
        if ((targetEntity != null) && (Entity.NONE != targetEntity.getSwarmTargetId())) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is swarming a Mek.");
        	premReturn = true;
        }

        // determine last valid step
        md.compile(game, attackEntity);
        for (final Enumeration<MoveStep> i = md.getSteps(); i.hasMoreElements();) {
            final MoveStep step = i.nextElement();
            if (!step.isLegal()) {
                break;
            }
            if (step.getType() == MovePath.STEP_DFA) {
                chargeStep = step;
            } else {
                chargeSrc = step.getPosition();
            }
        }

        // need to reach target
        if ((chargeStep == null)
                || !target.getPosition().equals(chargeStep.getPosition())) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"Could not reach target with movement");
    		premReturn = true;
        }

        // target must have moved already
        if ((targetEntity != null) && !targetEntity.isDone()) {
        	hitData = new ToHitData(TargetRoll.IMPOSSIBLE,"Target must be done with movement");
    		premReturn = true;
        }
        if (!premReturn){
    		hitData = toHit(game, attackerId, target, chargeSrc);
        }
        return hitData;
    }

    /**
     * To hit.
     *
     * @param game the game
     * @return the to hit data
     */
    public ToHitData toHit(final IGame game) {
        final Entity entity = game.getEntity(getEntityId());
        final Coords position = entity.getPosition();
        return toHit(game, getEntityId(), game.getTarget(getTargetType(),
                getTargetId()), position);
    }

    /**
     * To-hit number for a death from above attack, assuming that movement has
     * been handled.
     *
     * @param game the game
     * @param attackerId the attacker id
     * @param target the target
     * @param src the src
     * @return the to hit data
     */
    public static ToHitData toHit(final IGame game, final int attackerId,
            final Targetable target, final Coords src) {
        final Entity attackEntity = game.getEntity(attackerId);
        ToHitData hitDataTemp = null;
        Boolean premReturnTemp = false;
        // arguments legal?
        if (attackEntity == null) {
            throw new IllegalArgumentException("Attacker is null");
        }

        // Do to pretreatment of physical attacks, the target may be null.
        if (target == null) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "Target is null");
    		premReturnTemp = true;
        }
        int targetId;
        Entity targetEntity = null;
        if (target.getTargetType() == Targetable.TYPE_ENTITY) {
            targetEntity = (Entity) target;
            targetId = target.getTargetId();
        }
        else
        {
    			targetId = Entity.NONE;
     	}
        final GameOptions gameOptionsTemp = game.getOptions();
        final Entity entityTemp = (Entity)target;
        final Player playerTemp = entityTemp.getOwner();
        final Player player = attackEntity.getOwner();
        if (!gameOptionsTemp.booleanOption("friendly_fire")&& target.getTargetType() == Targetable.TYPE_ENTITY // NOPMD - this surely will never happen
        			&& entityTemp.getOwnerId() == attackEntity.getOwnerId() // NOPMD - this surely will never happen
        	 	|| playerTemp.getTeam() != Player.TEAM_NONE // NOPMD - this surely will never happen
        	&& player.getTeam() != Player.TEAM_NONE // NOPMD - this surely will never happen
        	&& player.getTeam() == playerTemp.getTeam()){
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "A friendly unit can never be the target of a direct attack.");
        	premReturnTemp = true;
        }

        final boolean targetInBuilding = Compute.isInBuilding(game, targetEntity);
        final IBoard board = game.getBoard();
        final IHex hexEntityPos = board.getHex(attackEntity.getPosition());
        final IHex hexTargetPos = board.getHex(target.getPosition());
        final int attackerElevation = attackEntity.getElevation() + hexEntityPos.getElevation();
        final int targetElevation = target.getElevation() + hexTargetPos.getElevation();
        final int attackerHeight = attackerElevation + attackEntity.getHeight();
        
        // check elevation of target flying VTOL
        final VTOL targetTemp = ((VTOL)target);
        final Boolean isFlying = targetTemp.isFlying();
        if (target instanceof VTOL && isFlying && targetElevation - attackerHeight > attackEntity.getJumpMP()) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Elevation difference to high");
        	premReturnTemp = true;
        }

        // can't target yourself
        if (attackEntity.equals(targetEntity)) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"You can't target yourself");
        	premReturnTemp = true;
        }

        // Infantry CAN'T dfa!!!
        if (attackEntity instanceof Infantry) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "Infantry can't dfa");
        	premReturnTemp = true;
        }

        // Can't target a transported entity.
        if (targetEntity != null && Entity.NONE != targetEntity.getTransportId()) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is a passenger.");
        	premReturnTemp = true;
        }

        // Can't target a entity conducting a swarm attack.
        if (targetEntity != null && Entity.NONE != targetEntity.getSwarmTargetId()) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is swarming a Mek.");
        	premReturnTemp = true;
        }

        // check range
        if (src.distance(target.getPosition()) > 1) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "Target not in range");
        	premReturnTemp = true;
        }

        // can't dfa while prone, even if you somehow did manage to jump
        if (attackEntity.isProne()) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "Attacker is prone");
        	premReturnTemp = true;
        }

        // can't attack mech making a different displacement attack
        if (targetEntity != null && targetEntity.hasDisplacementAttack()) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is already making a charge/DFA attack");
        	premReturnTemp = true;
        }

        // can't attack the target of another displacement attack
        final DisplacementAttackAction targetDisplace = targetEntity.findTargetedDisplacement();
        
        if (targetEntity != null && targetEntity.isTargetOfDisplacementAttack()
        		 && targetDisplace.getEntityId() != attackEntity.getId()){
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is the target of another charge/DFA");
        	premReturnTemp = true;
        }

        // Can't target units in buildings (from the outside).
        if (targetInBuilding) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Target is inside building");
        	premReturnTemp = true;
        }

        // Attacks against adjacent buildings automatically hit.
        if ((target.getTargetType() == Targetable.TYPE_BUILDING)
                || (target.getTargetType() == Targetable.TYPE_FUEL_TANK)
                || (target instanceof GunEmplacement)) {
        	hitDataTemp = new ToHitData(TargetRoll.AUTOMATIC_SUCCESS,"Targeting adjacent building.");
        	premReturnTemp = true;
        }

        // Can't target woods or ignite a building with a physical.
        if ((target.getTargetType() == Targetable.TYPE_BLDG_IGNITE)
                || (target.getTargetType() == Targetable.TYPE_HEX_CLEAR)
                || (target.getTargetType() == Targetable.TYPE_HEX_IGNITE)) {
        	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE, "Invalid attack");
        	premReturnTemp = true;
        }

        // Set the base BTH
        final Pilot pilot = attackEntity.getCrew();
         	final int base =pilot.getPiloting();
         	ToHitData toHit = new ToHitData(base, "base");

        // BMR(r), page 33. +3 modifier for DFA on infantry.
        if (targetEntity instanceof Infantry) {
            toHit.addModifier(3, "Infantry target");
        }

        // Battle Armor targets are hard for Meks and Tanks to hit.
        if (targetEntity instanceof BattleArmor) {
            toHit.addModifier(1, "battle armor target");
        }

        // attacker movement
        toHit.append(Compute.getAttackerMovementModifier(game, attackerId,
                IEntityMovementType.MOVE_JUMP));

        // target movement
        toHit.append(Compute.getTargetMovementModifier(game, targetId));

        // piloting skill differential
        final Pilot crew = attackEntity.getCrew();
        final Pilot crewTemp = targetEntity.getCrew();
        final int piloting =  crew.getPiloting();
        final int pilotingTemp = crewTemp.getPiloting();
        if (targetEntity != null && piloting != pilotingTemp){
        	toHit.addModifier(piloting - pilotingTemp, "piloting skill differential");
       
        }

        // attacker is spotting
        if (attackEntity.isSpotting()) {
            toHit.addModifier(+1, "attacker is spotting");
        }

        // target prone
        if ((targetEntity != null) && targetEntity.isProne()) {
            toHit.addModifier(-2, "target prone and adjacent");
        }

        // If it has a torso-mounted cockpit and two head sensor hits or three
        // sensor hits...
        // It gets a =4 penalty for being blind!
        final Mech mech = ((Mech) attackEntity);
		final int mount = Mech.COCKPIT_TORSO_MOUNTED;
        if ((attackEntity instanceof Mech) && mech.getCockpitType() == mount) {
        	final int sensorHits = attackEntity.getBadCriticals(CriticalSlot.TYPE_SYSTEM,Mech.SYSTEM_SENSORS, Mech.LOC_HEAD);
            final int sensorHits2 = attackEntity.getBadCriticals(CriticalSlot.TYPE_SYSTEM,
                    Mech.SYSTEM_SENSORS, Mech.LOC_CT);
            if ((sensorHits + sensorHits2) == 3) {
            	hitDataTemp = new ToHitData(TargetRoll.IMPOSSIBLE,"Sensors Completely Destroyed for Torso-Mounted Cockpit");
            	premReturnTemp = true;
            } else if (sensorHits == 2) {
                toHit.addModifier(4,
                        "Head Sensors Destroyed for Torso-Mounted Cockpit");
            }
        }

        // target immobile
        toHit.append(Compute.getImmobileMod(targetEntity));

        toHit.append(nightModifiers(game, target, null, attackEntity, false));

        Compute.modifyPhysicalBTHForAdvantages(attackEntity, targetEntity, toHit, game);

        //evading bonuses (
        if(targetEntity.isEvading()) {
            toHit.addModifier(targetEntity.getEvasionBonus(), "target is evading");
        }
        toHit = entityType(src, targetEntity, toHit);
        
        //Attacking Weight Class Modifier.
        final GameOptions gameOptions = game.getOptions();
        final Boolean gameOption = gameOptions.booleanOption("tacops_attack_physical_psr");
        if ( gameOption ) {
        	if ( attackEntity.getWeightClass() == EntityWeightClass.WEIGHT_LIGHT ) {
                 
                toHit.addModifier(-2, "Weight Class Attack Modifier");
            }
                 else if ( attackEntity.getWeightClass() == EntityWeightClass.WEIGHT_MEDIUM ) {
                toHit.addModifier(-1, "Weight Class Attack Modifier");
            }
        }

        if ((attackEntity instanceof Mech) && ((Mech)attackEntity).hasIndustrialTSM()) {
            toHit.addModifier(2, "industrial TSM");
        }

        // done!
        if (!premReturnTemp){
    		 	hitDataTemp = toHit;
    		 	}
    		 	return hitDataTemp;
        
    }
    
    /**
     * Entity type.
     *
     * @param src the src
     * @param targetEntity the target entity
     * @param toHit the to hit
     * @return the to hit data
     */
    private static ToHitData entityType(final Coords src, final Entity targetEntity, final ToHitData toHit) {
    if (targetEntity instanceof Tank) {
        toHit.setSideTable(ToHitData.SIDE_FRONT);
        toHit.setHitTable(ToHitData.HIT_NORMAL);
    } else if (targetEntity.isProne()) {
        toHit.setSideTable(ToHitData.SIDE_REAR);
        toHit.setHitTable(ToHitData.HIT_NORMAL);
    } else {
        toHit.setSideTable(targetEntity.sideTable(src));
        toHit.setHitTable(ToHitData.HIT_PUNCH);
    }
    return toHit;
    }
    
    /**
     * Checks for talons.
     *
     * @param entity the entity
     * @return true, if successful
     */
    public static boolean hasTalons(Entity entity){
    	Boolean hasTalons;
        if ( entity instanceof Mech ){

            if ( entity instanceof BipedMech ){

                hasTalons=entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_RLEG) && entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_RLEG) || (entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_LLEG) && entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_LLEG));
            }else{
                hasTalons=entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_RLEG) && entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_RLEG) || (entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_LLEG) && entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_LLEG)) || ((entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_RARM)) && (entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_RARM) || (entity.hasWorkingMisc(MiscType.F_TALON, -1, Mech.LOC_LARM) && entity.hasWorkingSystem(Mech.ACTUATOR_FOOT, Mech.LOC_LARM))));

            }
        }

        else{
        	hasTalons=false;
        }
        return hasTalons;
    }
}
